package com.industry.framework.file.local;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class LocalFileClient {

    private static final Logger log = LoggerFactory.getLogger(LocalFileClient.class);
    private String baseDir;

    public LocalFileClient(String baseDir) {
        this.baseDir = baseDir;
    }

    public void upload(String sourcePath, String targetPath) {
        log.info("upload file from {} to {}", sourcePath, targetPath);
        try {
            Path source = Paths.get(sourcePath);
            Path target = Paths.get(baseDir, targetPath);

            Files.createDirectories(target.getParent());

            Files.copy(source, target);
            log.info("upload file {} success." , target);
        } catch (IOException e) {
            log.error("upload file {} failed.", sourcePath, e);
            throw new RuntimeException("文件上传失败", e);
        }
    }

    public void download(String sourcePath, String targetPath) {
        try {
            Path source = Paths.get(baseDir, sourcePath);
            Path target = Paths.get(targetPath);

            Files.createDirectories(target.getParent());

            Files.copy(source, target);
            log.info("文件下载成功: {}", sourcePath);
        } catch (IOException e) {
            log.error("文件下载失败", e);
            throw new RuntimeException("文件下载失败", e);
        }
    }
}
